<template>
    <el-select :disabled="disabled" v-model="model" placeholder="请选择" style="width:100%" @change="change">
        <el-option v-for="item in list" :key="item.areaId" :label="item.areaName" :value="item.areaId">
        </el-option>
    </el-select>
</template>

<script>
import { queryAllAreaByCityId } from 'api/common';

export default {
    props: {
        value: {
            type: [String, Number]
        },
        city: {
            type: [String, Number],
            default: ''
        },
        disabled: {
            type: Boolean,
            required: false
        }
    },
    computed: {
        model: {
            get() {
                if (this.list) {
                    if (this.list.some(item => item.areaId == this.value)) {
                        let areaObj = this.list.find((item) => {
                            return item.areaId === this.value;
                        });
                        this.$emit('getAreaName', areaObj.areaName); 
                        return this.value;
                    } else {
                        this.$emit('input', '');
                        return '';
                    }
                } else {
                    return '';
                }
            },
            set(val) {
                this.$emit('input', val);
            }
        }
    },
    data() {
        return {
            list: null
        }
    },
    watch: {
        city(val) {
            // console.log('cccccccccc', val);
            this.getList();
            // this.$emit('input', '');
        }
    },
    created() {
        this.getList();
    },
    methods: {
        getList() {
            this.list = null;

            if (this.city) {
                let city = this.city; // 请求结束时，city没变化再回填
                queryAllAreaByCityId(this.city).then(res => {
                    if (res.data.content.length && this.city == city) {
                        this.list = res.data.content;
                        this.list.unshift({
                            areaId: '',
                            areaName: '请选择'
                        });
                    }
                }).catch(res => {
                    setTimeout(() => {
                        this.getList();
                    }, Math.random().toFixed(3)*1500)
                });
            } else {
                this.$emit('input', '');
            }
        },
        change(val) {
            this.$emit('change', val);
        }
    }
}
</script>

<style>

</style>
